const app = getApp()
const $api = require('../../utils/api.js').API;
Page({
    data: {
        id:0,
        list:{},
        imgUrl:app.globalData.imgUrl,
        cartShow:false,
        money:0.00,
        scoreTrue:false,
        integral:0.00,
        payOk:false,
        address:{},
        addid:0,
        str:'',
        num:'',

        red:0,
        redTrue:false,
        payScore:0,
        payRed:0,
        payMoney:0,
        fee:12.00,
        status:0,
        redShow:true,
        scoreShow:true,
        payTrue:true
    },
    onShow: function(){
        let pages = getCurrentPages();
        // 数组中索引最大的页面--当前页面
        let currentPage = pages[pages.length-1];

        var e = currentPage.options
        if(e.str == 24){
            this.setData({
                redShow:false
            })
        }
        // 打印出当前页面中的 options
        this.getInfo(e.str,e.num)
        this.setData({
            str:e.str,
            num:e.num
        })
        this.getUserScore()
        this.getAddress()
    },
    getAddress:function(){
        var that = this
        var data = {'uid':wx.getStorageSync('uid')}
        $api.get('address/info',data).then(res => {
            //请求成功
            if(res.data.code == 1){
                that.setData({
                    address:res.data.data,
                    addid:res.data.data.id
                })
            }else{
                that.setData({
                    address:false,
                })
            }
        })
    },
    getInfo:function(id,num){
        var that = this
        var data = {'id':id,'num':num}
        $api.get('score/orderAll',data).then(res =>{
            //请求成功
            if(res.data.code == 1){
                var list = res.data.data
                var money = 0;
                for(var x in list){
                    money += list[x]['price'] * list[x]['num']
                }
                that.setData({
                    list:list,
                    money:money
                })
            }
        }).catch(err => {
            //请求失败
            //console.log('job','请求失败');
        })
    },
    payclose:function(){
        this.setData({
            payOk:false
        })
    },
    getUserScore:function(){
        var that = this
        var data = {'uid':wx.getStorageSync('uid')}
        $api.get('member/info',data).then(res => {
            //请求成功
            if(res.data.code == 1){
                if(res.data.data.status !== 3){
                    that.setData({
                        scoreShow:false
                    })
                }else{
                    if(res.data.data.integral <= 0){
                        that.setData({
                            scoreShow:false
                        })
                    }
                    if(res.data.data.money <= 0){
                        that.setData({
                            redShow:false
                        })
                    }
                }
                that.setData({
                    integral:res.data.data.integral,
                    red:res.data.data.money,
                    status:res.data.data.status
                })
            }
        }).catch(err => {
            //请求失败
            //console.log('job','请求失败');
        })
    },
    payquery:function(){
        //是否使用积分
        var payScore = 0;
        var payMoney = 0;
        var payRed = 0;


        if(this.data.str == 24){
            if(parseFloat(this.data.money) > parseFloat(this.data.integral)){
                wx.showToast({
                    title:'积分不足',
                    duration:3000,
                    mask:true, 
                    icon:'none',
                })
                return;
            }
            var payScore = this.data.money;
        }else{
            if(!this.data.addid){
                wx.showToast({
                    title:'选择收货地址',
                    duration:3000,
                    mask:true, 
                    icon:'none',
                })
                return;
            }

            if(this.data.str == 25){
                this.setData({
                    fee:0
                })
            }
            if(this.data.scoreTrue){
                //积分是否可以完全抵扣 积分大于支付的金额
                if(this.data.integral - this.data.money > 0){
                    //积分大于支付的金额  完全抵扣
                    var payScore = this.data.money
                }else{
                    var payScore = this.data.integral
                }
            }
            //红包余额  抵扣
            if(this.data.redTrue){
                //判断积分是否够完全抵扣 
                if(payScore < this.data.money){
                    if(this.data.money - payScore - this.data.red > 0){//积分余额好不够
                        var payRed = this.data.red
                    }else{
                        var payRed = parseFloat(this.data.money) - parseFloat(payScore)
                        payRed = payRed.toFixed(2);
                    }
                }
            }
            if(this.data.money - payScore - payRed > 0){
                var payMoney = parseFloat(this.data.money) - parseFloat(payScore) - parseFloat(payRed)
                payMoney = payMoney.toFixed(2);
            }
            if(this.data.money < 500){
                var payMoney = parseFloat(payMoney) + parseFloat(this.data.fee)
                payMoney = payMoney.toFixed(2);
            }
        }
        this.setData({
            payOk:true,
            payScore:payScore,
            payRed:payRed,
            payMoney:payMoney
        })
    },
    plus:function(e){
        var index = e.currentTarget.dataset.index
        var list = this.data.list
        list[index]['num'] ++;
        var money = parseFloat(this.data.money) + parseFloat(list[index]['price']);
        money = money.toFixed(2);
        this.setData({
            money:money,
            list:list
        })

    },
    less:function(e){
        var index = e.currentTarget.dataset.index
        var list = this.data.list
        if(list[index]['num'] > 1){
            list[index]['num'] --;
            var money = parseFloat(this.data.money) - parseFloat(list[index]['price']);
            money = money.toFixed(2);
            this.setData({
                money:money,
                list:list
            })
        }
    },
    bindAcceptRule:function(e){
        var name = e.target.dataset.name
        if (e.detail.value.length !== 0) {
            this.setData({
                [name]:true
            })
        }else{
            this.setData({
                [name]:false
            })
        }
    },
    pay:function(){
        if(this.data.money < 500 && this.data.str !== 24 && this.data.str !== 25){
            var fee = this.data.fee
        }else{
            var fee = 0
        }
        var str = ''
        var num = ''
        for(var x in this.data.list){
            if(str == ''){
                str = this.data.list[x]['goods_id']
                num = this.data.list[x]['num']
            }else{
                str = str + ',' + this.data.list[x]['goods_id']
                num = num + ',' + this.data.list[x]['num']
            }
        }
        var data = {
            'uid':wx.getStorageSync('uid'),
            'payMoney':this.data.payMoney, //支付金额
            'payScore':this.data.payScore, //抵扣积分
            'payRed':this.data.payRed, //抵扣余额
            'money':this.data.money,//订单总价
            'goods_id':str,
            'num':num,
            'addid':this.data.addid,
            'fee':fee,//快递费
        }
        var that = this
        this.setData({
            payTrue:false
        })
        $api.post('wxpay/pay',data).then(res =>{
            that.setData({
                payTrue:true
            })
            if(res.data.code == 1){
                if(that.data.payMoney > 0){
                    that.getPayResult(res);
                }else{
                    that.setData({
                        payOk:false
                    })
                    wx.showToast({
                        title:'兑换成功',
                        duration:3000,
                        mask:true, 
                        icon:'success',
                        success:function(){
                            setTimeout(function(){
                                wx.switchTab({
                                    url: '../user/index'
                                  })
                            },3000) //延迟时间 这里是
                        }
                    })
                }
            }else{
                wx.showToast({
                    title:res.data.msg,
                    duration:3000,
                    mask:true, 
                    icon:'none',
                })
            }
        }).catch(err => {
            //请求失败
            //console.log('job','请求失败');
        })
    },
    getPayResult:function(e){
        var that = this
        // 签权调起支付 
        wx.requestPayment({
            'timeStamp': e.data.data.timeStamp,
            'nonceStr': e.data.data.nonceStr,
            'package': e.data.data.package,
            'signType': e.data.data.signType,
            'paySign': e.data.data.paySign,
            'success': function (res){
                that.setData({
                    payOk:false
                })
                that.payNotify(e.data.data.orderid)
            },
            'fail': function (res){
                //console.log("支付失败",res)
            },     
        })
    },
    payNotify:function(orderid){
        console.log(orderid)
        var data = {'orderid':orderid}
        $api.post('wxpay/payNotify',data).then(res => {
              if(res.data.code == 1){
                wx.showToast({
                    title:'支付成功,跳转至订单页面',
                    duration:3000,
                    mask:true, 
                    icon:'success',
                })
                wx.switchTab({
                    url: '../user/index'
                  })
              }
         }).catch(err => {
             //请求失败
             //console.log('job','请求失败');
         })
    },
    address:function(){
        wx.navigateTo({
            url:'/pages/user/address/index?str='+this.data.str+'&num='+this.data.num
        })
    },
    onShareAppMessage: function() {
        return {
            title: this.data.info.name+"-天意美业直通车",
            path: "/pages/index/index?puid="+wx.getStorageSync('uid')
        };
    }
});